package com.xuecheng.content.controller;

import com.xuecheng.commons.model.vo.CoursePubVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.web.exceptions.BusinessException;
import freemarker.template.TemplateException;
import io.minio.errors.*;
import org.springframework.web.bind.annotation.*;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程发布前端控制器
 * </p>
 *
 * @author 七安
 */
@Slf4j
@RestController
@RequestMapping("/coursePub")
public class CoursePubController {

    @Autowired
    private CoursePubService coursePubService;

    /**
     * 课程发布预览
     *
     * @param courseBaseId id
     * @return 结果
     */
    @GetMapping("/preview/{courseBaseId}")
    public ModelAndView releasePreview(@PathVariable("courseBaseId") Long courseBaseId) throws BusinessException {
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        //指定模板
        modelAndView.setViewName("learing_article");
        //调用service处理
        Map<String, Object> map = coursePubService.releasePreview(courseBaseId);
        modelAndView.addAllObjects(map);
        return modelAndView;
    }

    /**
     * 课程发布
     *
     * @param courseBaseId 课程id
     * @return 发布结果
     */
    @PostMapping("/publish/{courseBaseId}")
    public ResponseResult coursePublish(@PathVariable("courseBaseId") Long courseBaseId) throws BusinessException, ServerException, TemplateException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return coursePubService.coursePublish(courseBaseId);
    }

    /**
     * 查询所有
     *
     * @return 所有已发布的课程
     */
    @GetMapping("/findAll")
    public ResponseResult<List<CoursePubVo>> findAll() {
        List<CoursePub> coursePubs = coursePubService.list();
        //转成vo对象并返回
        return ResponseResult.okResult(BeanHelper.copyWithCollection(coursePubs, CoursePubVo.class));
    }

    @GetMapping("/{id}")
    public ResponseResult<CoursePubVo> findById(@PathVariable("id") Long id) {
        CoursePub coursePub = coursePubService.getById(id);
        //转Vo对象并返回
        return ResponseResult.okResult(BeanHelper.copyProperties(coursePub, CoursePubVo.class));
    }
}
